package unipi.helpers;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import unipi.database.User;

public class LoginCookie 
{	
	public static void Set(String uid, String pass, boolean remember, HttpServletResponse response)
	{
		int cookieAge = 365*24*60*60;
		
		Cookie userCookie = new Cookie("userid", uid);
		if(remember) userCookie.setMaxAge(cookieAge); 
		
		Cookie passCookie = new Cookie("passhash", Hash.SHA1(pass));
		if(remember) passCookie.setMaxAge(cookieAge);
		
		response.addCookie(userCookie);
		response.addCookie(passCookie);	
		
	}
	
	public static boolean authCookie(HttpServletRequest request)
	{
		String[] cookie = LoginCookie.Get(request);
		
		String userid = cookie[0];
		String passhash = cookie[1];
		
		if(!Validator.isNumber(userid) || !Validator.isValid(passhash)) return false;
		
		if(userid == "" || passhash == "")
			return false;			
		else
			return User.authUserCookie(userid, passhash);
			
	}
	
	public static void Delete(HttpServletResponse response, HttpServletRequest request)
	{
		Cookie[] cookies = request.getCookies();
		if(cookies != null)
		{
			for(Cookie ck : cookies)
			{
				if(ck.getName().equals("userid"))
				{
					ck.setMaxAge(0);
					response.addCookie(ck);
				}
					
				if(ck.getName().equals("passhash"))
				{
					ck.setMaxAge(0);
					response.addCookie(ck);
				}
			}			
		}		
	}
	
	public static String[] Get(HttpServletRequest request)
	{
		String[] data = new String[]{"", ""};
		
		Cookie[] cookies = request.getCookies();
		if(cookies != null)
		{
			for(Cookie ck : cookies)
			{
				if(ck.getName().equals("userid"))
					data[0] = ck.getValue();
				
				if(ck.getName().equals("passhash"))
					data[1] = ck.getValue(); 
			}			
		}
		
		return data;		
	}

}
